import {
  Controller,
  HttpException,
  HttpStatus,
  Post,
  Request,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { diskStorage } from 'multer';
import { extname } from 'path';
import * as fs from 'fs';
import * as COS from 'cos-nodejs-sdk-v5';
import { promisify } from 'util';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiException } from '../common/filter/http-exception/api.exception';
import { ApiErrorCode } from '../common/enums/api-error-code.enum';
import { Public } from '../public/public.decorator';

const unlinkAsync = promisify(fs.unlink);
@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  /**
   * 图片上传
   * @param req
   * @param file
   */
  @Public()
  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, cb) => {
          const randomName = Array(32)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          return cb(null, `${randomName}${extname(file.originalname)}`);
        },
      }),
    }),
  )
  async upload(@Request() req: any, @UploadedFile() file: any) {
    const cos = new COS({
      SecretId: process.env.TENCENT_SECRET_ID,
      SecretKey: process.env.TENCENT_SECRET_KEY,
    });
    const uploadType = req.headers['x-upload-type'];
    const suffix = file.originalname.split('.')[1];
    let uploadKey = '';
    if (uploadType === undefined) {
      throw new ApiException('文件上传类型不能为空', ApiErrorCode.UPLOAD_ERROR);
    } else if (uploadType === 'avatar') {
      uploadKey = 'avatar' + new Date().getTime() + '.' + suffix;
    } else if (uploadType === 'moment') {
      uploadKey = 'moment' + new Date().getTime() + '.' + suffix;
    } else if (uploadType === 'cover') {
      uploadKey = 'cover' + new Date().getTime() + '.' + suffix;
    } else {
      throw new ApiException('文件上传类型错误', ApiErrorCode.UPLOAD_ERROR);
    }
    try {
      const options = {
        Bucket: 'sujualpha-1307553737',
        Region: 'ap-shanghai',
        Key: uploadKey,
        Headers: {
          'Content-Disposition': 'inline',
        },
        Body: fs.createReadStream(`./uploads/${file.filename}`),
      };
      const result = await cos.putObject(options);
      const location = result.Location;
      const url = `https://${location}`;
      await unlinkAsync(`./uploads/${file.filename}`);
      return {
        url,
        filename: file.filename,
      };
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
